"""
Video thumbnail generation for PowerPoint presentations.
"""

import tempfile
from pathlib import Path
from typing import Optional

try:
    import imageio.v3 as iio
    from PIL import Image
    IMAGEIO_AVAILABLE = True
except ImportError:
    IMAGEIO_AVAILABLE = False


class ThumbnailGenerator:
    """Generates thumbnails from video files."""
    
    def __init__(self):
        self.cache_dir = Path(tempfile.gettempdir()) / "md2ppt_thumbnails"
        self.cache_dir.mkdir(exist_ok=True)
    
    def extract_video_thumbnail(self, video_path: str, output_size: Optional[tuple] = None) -> Optional[Path]:
        """
        Extract the first frame from a video and save as thumbnail.
        
        Args:
            video_path: Path to the video file
            output_size: Optional tuple of (width, height). If None, uses video's aspect ratio
            
        Returns:
            Path to the generated thumbnail, or None if extraction failed
        """
        if not IMAGEIO_AVAILABLE:
            return None
        
        try:
            video_path = Path(video_path)
            if not video_path.exists():
                return None
            
            # Get video info to determine aspect ratio
            video_info = self.get_video_info(str(video_path))
            if not video_info:
                return None
            
            # Calculate output size based on video aspect ratio if not provided
            if output_size is None:
                # Use video's natural aspect ratio with reasonable resolution
                aspect_ratio = video_info['aspect_ratio']
                if aspect_ratio >= 1.0:
                    # Landscape or square - base on width
                    output_size = (480, int(480 / aspect_ratio))
                else:
                    # Portrait - base on height
                    output_size = (int(480 * aspect_ratio), 480)
            
            # Generate cache filename based on video path and modification time
            video_mtime = video_path.stat().st_mtime
            cache_key = f"{video_path.stem}_{int(video_mtime)}_{output_size[0]}x{output_size[1]}"
            thumbnail_path = self.cache_dir / f"{cache_key}.jpg"
            
            # Return cached thumbnail if it exists
            if thumbnail_path.exists():
                return thumbnail_path
            
            # Extract first frame
            frame = iio.imread(str(video_path), index=0)
            
            # Convert to PIL Image
            img = Image.fromarray(frame)
            
            # Resize to target size while maintaining aspect ratio
            img = self._resize_with_aspect_ratio(img, output_size)
            
            # Save as JPEG with good quality
            img.save(thumbnail_path, 'JPEG', quality=85, optimize=True)
            
            return thumbnail_path
            
        except Exception as e:
            print(f"Warning: Could not extract thumbnail from {video_path}: {e}")
            return None
    
    def _resize_with_aspect_ratio(self, img: Image.Image, target_size: tuple) -> Image.Image:
        """
        Resize image to target size while maintaining aspect ratio.
        For video thumbnails, we want to preserve the exact aspect ratio without padding.
        """
        target_width, target_height = target_size
        original_width, original_height = img.size
        
        # Calculate target aspect ratio
        target_aspect = target_width / target_height
        original_aspect = original_width / original_height
        
        # If the target size matches the video aspect ratio (within tolerance),
        # resize directly without padding
        if abs(target_aspect - original_aspect) < 0.01:
            return img.resize(target_size, Image.Resampling.LANCZOS)
        
        # Otherwise, use the original behavior with padding
        # Calculate scaling factor to fit within target size
        scale_width = target_width / original_width
        scale_height = target_height / original_height
        scale = min(scale_width, scale_height)
        
        # Calculate new dimensions
        new_width = int(original_width * scale)
        new_height = int(original_height * scale)
        
        # Resize image
        img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
        
        # Create new image with target size and black background
        result = Image.new('RGB', target_size, color='black')
        
        # Paste resized image in center
        x_offset = (target_width - new_width) // 2
        y_offset = (target_height - new_height) // 2
        result.paste(img, (x_offset, y_offset))
        
        return result
    
    def get_video_info(self, video_path: str) -> dict:
        """
        Get basic information about a video file.
        
        Returns:
            Dictionary with video information, or empty dict if failed
        """
        if not IMAGEIO_AVAILABLE:
            return {}
        
        try:
            props = iio.improps(video_path)
            height, width = props.shape[1:3]  # shape is (frames, height, width, channels)
            
            return {
                'width': width,
                'height': height,
                'channels': props.shape[3] if len(props.shape) > 3 else 3,
                'dtype': str(props.dtype),
                'aspect_ratio': width / height
            }
        except Exception:
            return {}
    
    def cleanup_cache(self, max_age_days: int = 7):
        """
        Clean up old thumbnail cache files.
        
        Args:
            max_age_days: Remove cache files older than this many days
        """
        import time
        
        cutoff_time = time.time() - (max_age_days * 24 * 60 * 60)
        
        try:
            for cache_file in self.cache_dir.glob("*.jpg"):
                if cache_file.stat().st_mtime < cutoff_time:
                    cache_file.unlink()
        except Exception as e:
            print(f"Warning: Could not clean thumbnail cache: {e}")
    
    def is_available(self) -> bool:
        """Check if video thumbnail generation is available."""
        return IMAGEIO_AVAILABLE